<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;

/**
 * 文旅订单
 *
 * @icon fa fa-circle-o
 */
class OrderTravel extends Backend
{

    /**
     * OrserTravel模型对象
     * @var \app\admin\model\order\OrserTravel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\OrderTravel;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','order_no','title','price','num','total_price','name','phone','address','status','pay_time','createtime','express_company','express_no','ship_time','complete_time']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 发货
     */
    public function ship($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $result = false;
                try {
                    $result = $row->allowField(true)->save([
                        'express_company' => $params['express_company'],
                        'express_code' => $params['express_code'],
                        'express_no' => $params['express_no'],
                        'status' => 2,
                        'ship_time' => time()
                    ]);
                    
                    // 发货成功后创建系统消息
                    if ($result !== false) {
                        \app\common\model\SystemMessage::create([
                            'user_id' => $row->user_id,
                            'type' => 'travel',
                            'title' => '订单已发货',
                            'content' => "您的文旅订单 {$row->order_no} 已发货，物流公司：{$params['express_company']}，物流单号：{$params['express_no']}，请注意查收",
                            'order_id' => $row->id,
                            'order_no' => $row->order_no
                        ]);
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取物流公司列表
        $expressList = \think\Db::name('expressquery')->field('name,express,coding')->select();
        $this->view->assign("expressList", $expressList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            try {
                $result = null;
                $out_request_no = $row->out_request_no;
                if(!$out_request_no){
                    $out_request_no = date('YmdHis') . rand(1000, 9999);
                }
                if ($row->pay_type == 'alipay') {
                    $result = \app\common\library\Refund::alipay($row->order_no, $params['refund_amount'], $params['reason'],$out_request_no);
                } else if ($row->pay_type == 'wechat') {
                    $result = \app\common\library\Refund::wechat($row->order_no, $row->total_price, $params['refund_amount'], $params['reason'],$out_request_no);
                }
                if ($result && $result['status']) {
                    // 更新订单状态为已退款
                    $row->status = 5; // 已退款
                    $row->refund_time = time();
                    $row->refund_amount = $params['refund_amount'];
                    $row->refund_reason = $params['reason'];
                    $row->out_request_no = $out_request_no;
                    $row->save();
                    // 记录用户消费记录
                    \think\Db::name('user_consume_log')->insert([
                        'user_id' => $row->user_id,
                        'type' => 'refund',
                        'target_id' => $row->id,
                        'target_title' => '订单退款',
                        'amount' => $params['refund_amount'],
                        'createtime' => time()
                    ]);
                    $this->success('退款成功');
                }else{
                    $this->error('退款失败'.$result['message']);
                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
